package name.sakanacatcher.util;

import com.alibaba.fastjson.JSONObject;
import name.sakanacatcher.config.SecurityConfig;
import name.sakanacatcher.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
@Component
public class RequestUtil {
    @Autowired
    SecurityConfig securityConfig;
    @Autowired
    TokenUtil tokenUtil;

    @Autowired
    ResultUtil resultUtil;

    private HttpHeaders getHeader(){
        HttpHeaders headers = new HttpHeaders();
        headers.setBearerAuth(tokenUtil.generateToken("admin"));
        headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
        return headers;
    }

    public Map<String, Object> request(String url,HttpMethod method){
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> requestEntity = new HttpEntity<>(null, getHeader());
        ResponseEntity<String> resEntity = restTemplate.exchange(url.toString(), method, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(resEntity.getBody());
        return resultUtil.customResult(jsonObject.getInteger("status"),jsonObject.getString("message"),jsonObject.get("data"));
    }

    public Map<String, Object> request(String url,HttpMethod method,Map<String,Object> param){
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<Map<String,Object>> requestEntity = new HttpEntity<Map<String,Object>>(param, getHeader());
        ResponseEntity<String> resEntity = restTemplate.exchange(url.toString(), method, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(resEntity.getBody());
        return resultUtil.customResult(jsonObject.getInteger("status"),jsonObject.getString("message"),jsonObject.get("data"));
    }
    public Map<String, Object> upload(Map<String,Object> param){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf(MediaType.MULTIPART_FORM_DATA_VALUE));
        HttpEntity<Map<String,Object>> requestEntity = new HttpEntity<Map<String,Object>>(param,headers);
        ResponseEntity<String> resEntity = restTemplate.exchange("", HttpMethod.POST, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(resEntity.getBody());
        return resultUtil.customResult(jsonObject.getInteger("status"),jsonObject.getString("message"),jsonObject.get("data"));
    }
}
